/**
 * Created by WT-SUN on 2017/4/1.
 */
$(function () {
    $('#planTb').datagrid({
        view: detailview,
        rownumbers: true,//显示行号
        striped: true,
        fit: true,
        singleSelect: true,
        sortOrder: true,
        fitColumns: true,
        pagination: true,
        toolbar: '#toolbar',
        url: ROOT_PATH + '/occupationalHealth/medicalPlan/planTable.shtml',
        queryParams:{
            sort:'addTime',
            order:'desc'
        },
        detailFormatter:function(index,row){
            return '<div class="planddv" style="padding:0px 0"></div>';
        },
        onExpandRow: function(index,row){
            if (typeof ($('#lastIndex').val())!='undefined'&&$('#lastIndex').val()*1!=index){
                $(this).datagrid('collapseRow',$('#lastIndex').val());
                $('.planddv').empty();
            }
            var ddv = $(this).datagrid('getRowDetail',index).find('div.planddv');
            ddv.panel({
                border:false,
                cache:false,
                href:ROOT_PATH + '/occupationalHealth/medicalPlan/info.shtml?id=' + row.id+'&type=info',
                onLoad:function(){
                    $('#lastIndex').val(index);
                    $('#planTb').datagrid('fixDetailRowHeight',index);
                }
            });
            $('#planTb').datagrid('fixDetailRowHeight',index);
        },
        columns: [[
            {
                field: 'id',
                checkbox: true
            },
            {field: 'batch', title: '批次', width: 100, sortable: true},
            {field: 'yearAnnual', title: '年度', width: 100},
            {field: 'medicalCategory', title: '体检类别', width: 100},
            {field: 'startDate', title: '开始日期', width: 100, sortable: true},
            {field: 'endDate', title: '结束日期', width: 100},
            {field: 'phyNumber', title: '体检人数', width: 100, sortable: true},
            {field: 'realNumber', title: '实际人数', width: 100},
            {field: 'username', title: '登记人', width: 100},
            {field: 'deptname', title: '登记部门', width: 100},
            {field: 'addTime', title: '登记时间', width: 100},
        ]]
    });
    queryComboData();
    $('#btn_plan_add').on('click',function () {
        addPlans();
    });
    $('#btn_plan_delete').on('click',function () {
        deletePlans();
    });
    $('#btn_plan_edit').on('click',function () {
        editPlans();
    });
    $('#btn_clear').on("click", function () {
        $('#queryForm1').form('reset');
        $('#queryForm2').form('reset');
    });
    /**
     * 高级查询
     */
    $('#btn_advanced_search').on("click", function () {
        $('#queryForm2').toggle();
        $('#planTb').datagrid('resize');
    });
    queryYearthList("yearAnnual");
    queryDepartmentTree();

    /**
     * 绑定人员选择事件
     */
    $("#searchAddUser").textbox({
        iconWidth: 20,
        icons: [{
            iconCls: 'icon-add',
            handler: function(e){
                add_userId_func();
            }
        },{
            iconCls: 'icon-remove',
            handler: function(e){
                $(e.data.target).textbox('clear');

            }
        }]
    });
});
function queryDepartmentTree(){
    $.ajax({
        url:ROOT_PATH + '/permission/department/getDepartmentTree.shtml',//提交地址
        data:{parentId : 0},//将表单数据序列化
        type:"POST",
        dataType:"json",
        success:function(result){
            $('#searchAddDept').combotree(
                {
                    data:result,
                    prompt:'请选择',
                    require:true,
                    loadFilter:function(data){
                        var newData = new Array();
                        newData.push({id:"",text:'请选择'});
                        newData.push(data[0]);
                        return newData;
                    }
                }
            );
        }
    });
}
function queryComboData() {
    var code=CONSTANT.DictionaryTypeDefConstants.OHE_HEALTH_TYPE;
    var EMPTY_OPTION = {
     id: '',
     text: '请选择'
     };
    $.ajax({
        type: 'post',
        url: ROOT_PATH + '/permission/dictionary/queryDictionaryByDictionaryTypeCode.shtml',
        data: {code: code},
        dataType: "json",
        success: function (result) {
            $('#medicalCategoryQuery').combobox({
                 loadFilter: function (data) {
                 data.unshift(EMPTY_OPTION);
                 return data;
                 },
                data: result,
                prompt:'请选择',
                valueField: 'id',
                textField: 'text',
                editable: false,
                panelHeight: '200',
                onSelect: function (record) {

                }
            });
            //result = $.parseJSON(result);
        }
    });
}
var add_userId_func = function () {
    WindowManager.openLayer({
        type: 2,
        title: '选择人员信息',
        area: ['1150px', '70%'],
        content: ROOT_PATH + '/permission/user/simpleList.shtml?isMulti=0',
        callBack:function(data){
            getSelectedUser(data);
        }
    });
};
/**
 * 人员信息选择
 */
var getSelectedUser = function (data) {
    if(data.length>0){
        $("#searchAddUser").textbox('setValue', data[0].id).textbox('setText', data[0].realName);
    }
};
/**
 * 重新加载表格
 */
function reLoadData() {
    $('#planTb').datagrid('clearSelections');
    var queryParams1 = $('#queryForm1').serializeJson();
    var queryParams2 = $('#queryForm2').serializeJson();
    var queryParams = $.extend(queryParams1,queryParams2);
    queryParams["sort"] = 'addTime';
    queryParams["order"] = 'desc';
    $('#planTb').datagrid('options').queryParams = queryParams;
    $("#planTb").datagrid('reload', ROOT_PATH + '/occupationalHealth/medicalPlan/planTable.shtml');
}
/**
 * 打开弹框
 * @param title
 * @param content
 */
function openLayers(title, content) {
    layer.open({
        type: 2,
        resize: false,
        title: title,
        area: ['690px', '60%'],
        content: content
    });
}
/**
 * 打开新建体检计划框
 */
function addPlans() {
    var title = '新增体检计划';
    var content = ROOT_PATH + '/occupationalHealth/medicalPlan/add.shtml';
    openLayers(title, content);
}
/**
 * 删除计划
 */
function deletePlans() {
    var rows = $('#planTb').datagrid('getSelections');

    if (rows.length == 0) {
        layer.alert("选择需要删除的行！");
        return
    }
    var id = rows[0].id;
    layer.confirm('是否确定删除当前选中数据？', {
        btn: ['确定', '取消'] //按钮
    }, function () {
        $.ajax({
            type: 'post',
            url: ROOT_PATH + '/occupationalHealth/medicalPlan/deleteById.shtml',
            data: {id: id},
            dataType: "json",
            success: function (result) {
                //result = $.parseJSON(result);
                if (result.success) {
                    $('#planTb').datagrid('clearSelections');
                    reLoadData();
                    layer.msg('删除成功', {
                        icon: 1,
                        time: 1000
                    });
                }
                else {
                    layer.msg('删除失败', {
                        icon: 2,
                        time: 1000
                    });
                }
            }
        });
    });
}
/**
 * 编辑计划
 */
function editPlans() {
    var rows = $('#planTb').datagrid('getSelections');
    if (rows.length == 0) {
        layer.alert("选择需要编辑的行！");
        return
    }
    var id = rows[0].id;
    var title = '编辑体检计划';
    var content = ROOT_PATH + '/occupationalHealth/medicalPlan/info.shtml?id=' + id+'&type=edit';
    openLayers(title, content);
}
function queryYearthList(id){
    var date = new Date();
    var year = date.getFullYear();
    var yearthData = new Array();
    yearthData.push({id:"",text:"请选择"});
    for(var i =0;i<6;i++){
        var y = {id:year-i,text:(year-i)+'年'};
        yearthData.push(y);
    }
    $('#'+id).combobox(
        {
            data:yearthData,
            valueField:'id',
            textField:'text',
            editable:false
        }
    );
}